package cn.hua.trip.app.base.controller;

import cn.hua.trip.app.base.util.UserContext;
import cn.hua.trip.base.domain.User;
import cn.hua.trip.base.service.IUserService;
import cn.hua.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class SessionController {
    /*
    * 注册功能设计
    *
    * 资源:users
    * 访问方式:POST
    * 请求参数:email,password
    * 返回结果:json
    * */

    @Autowired
    private IUserService userService;

    @PostMapping("/sessions")
    public Object login(String email,String password){
        JSONResult result = new JSONResult();

        try {
            User user = userService.login(email, password);
           UserContext.setCurrentUser(user);
            //将用户数据返回给页面
            result.setData(user);
        }catch (Exception e){
            result.mark(e.getMessage());
        }
        return result;
    }


    //注销操作
    @DeleteMapping("/sessions")
    public Object logout(HttpSession session){
        JSONResult result = new JSONResult();
        session.invalidate();
        return result;
    }
}
